import { worker } from './initWorker.ts'
import { useLoginWsStorage } from '@/stores/ws.ts'
import {
  type LoginInitResType,
  type LoginSuccessType,
  type MessageType,
  type UserInfoType,
  type WsReqMsgContentType,
  type WsResMsgContentType,
} from '@/services/types.ts'
import { ElMessage } from 'element-plus'
import { LoginStatus, WsResponseMsgType } from '@/enums'
import { setToken, setUserInfo } from '@/utils/localStorageUtil.ts'
import { useUserStorage } from '@/stores/user.ts'
import { computedToken, getToken } from '@/services/request.ts'
import router from '@/router'
import { useChatStorage } from '@/stores/chat.ts'

/**
 * 主线程给子线程发送消息
 */
class WS {
  #tasks: WsReqMsgContentType[] = []
  // 连接是否准备好了
  #connectReady = false
  constructor() {
    // console.log('init')
    this.initConnect()
    // this.initConnect()
    // 收到消息
    // worker.addEventListener('message', this.onWorkerMsg)

    // 后台重试次数达到上限之后，tab 获取焦点再重试
    // document.addEventListener('visibilitychange', () => {
    //     if (!document.hidden && !this.#connectReady) {
    //         this.initConnect()
    //     }
    //
    //     // 获得焦点停止消息闪烁
    //     if (!document.hidden) {
    //         shakeTitle.clear()
    //     }
    // })
  }

  initConnect = () => {
    const token = localStorage.getItem('TOKEN')
    // 如果token 是 null, 而且 localStorage 的用户信息有值，需要清空用户信息
    if (token === null && localStorage.getItem('USER_INFO')) {
      localStorage.removeItem('USER_INFO')
    }
    // 发送消息给子线程去连接websocket
    // 初始化 ws
    worker.postMessage(`{"type":"initWS","value":${token ? `"${token}"` : null}}`)
    worker.addEventListener('message', this.onWorkerMsg)
  }

  // 监听子线程发过来的消息
  onWorkerMsg = (e: MessageEvent<any>) => {
    const params: { type: string; value: unknown } = JSON.parse(e.data)
    switch (params.type) {
      case 'message': {
        // 接收到websocket服务器发送来的消息
        this.onMessage(params.value as string)
        break
      }
      case 'open': {
        // alert("建立websocket连接")
        this.#dealTasks()
        // wsLoginStore.loginStatus = LoginStatus.Success
        break
      }
      case 'close':
      case 'error': {
        // this.#onClose()
        break
      }
    }
  }

  #dealTasks = () => {
    this.#connectReady = true
    // 先探测登录态
    // this.#detectionLoginStatus()

    // setTimeout(() => {
    //     const userStore = useUserStore()
    //     const loginStore = useWsLoginStore()
    //     if (userStore.isSign) {
    //         // 处理堆积的任务
    //         this.#tasks.forEach((task) => {
    //             this.send(task)
    //         })
    //         // 清空缓存的消息
    //         this.#tasks = []
    //     } else {
    //         // 如果没登录，而且已经请求了登录二维码，就要更新登录二维码。
    //         loginStore.loginQrCode && loginStore.getLoginQrCode()
    //     }
    // }, 500)
  }

  onMessage = (value: string) => {
    //接收到消息
    const params: WsResMsgContentType = JSON.parse(value)
    //登录仓库数据
    const loginStorage = useLoginWsStorage()
    //用户仓库数据
    const userStorage = useUserStorage()
    //会话仓库数据
    const chatStorage = useChatStorage()

    switch (params.type) {
      // 接收登录跳转连接
      case WsResponseMsgType.LOGIN_URL: {
        //请求的登录url
        const data = params.data as LoginInitResType
        loginStorage.authLoginUrl = data.loginUrl
        break
      }
      case WsResponseMsgType.AUTHORIZATION: {
        //微信扫码登录用户等待确认
        //或者网页第三方等待确认
        loginStorage.loginStatus = LoginStatus.Waiting
        break
      }
      case WsResponseMsgType.INVALIDATE_TOKEN: {
        //登录态失效
        ElMessage.error('token失效')
        userStorage.userLoginOut()
        computedToken.get()
        //loginStorage.loginStatus = LoginStatus.Init
        loginStorage.resetLoginStatus()
        break
      }

      case WsResponseMsgType.LOGIN_SUCCESS: {
        //登录成功
        const { token, ...successData } = params.data as LoginSuccessType
        ElMessage.success('用户登录成功')
        userStorage.userLoginIn({ ...userStorage.userInfo, ...successData } as UserInfoType, token)

        //清除请求发送请求的token
        computedToken.clear()
        computedToken.get()

        // 清空登录二维码
        loginStorage.authLoginUrl = ''
        //设置登录状态
        loginStorage.loginStatus = LoginStatus.Success
        //跳回主页
        router.push({
          // name: name,
          path: userStorage.currentPath,
        })
        //获取会话列表
        chatStorage.getSessionList(false)
        break
      }

      case WsResponseMsgType.RECEIVE_MESSAGE:{
        //接收到新消息
       const res = params.data as MessageType;
        ElMessage.success('接收到一条消息是：'+res.messageInfo.body.content)
      }

      default: {
        return
        break
      }
    }
  }

  send = (params: WsReqMsgContentType) => {
    if (this.#connectReady) {
      this.#send(params)
    } else {
      this.#tasks.push(params)
    }
  }

  // 将主线程消息发送给子线程
  #send(msg: WsReqMsgContentType) {
    worker.postMessage(
      `{"type":"message","value":${typeof msg === 'string' ? msg : JSON.stringify(msg)}}`,
    )
  }
}

export default new WS()
